package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        获取请求url
        String url = request.getRequestURI();
//        登录不拦截
        if (url.contains("login")) {
            filterChain.doFilter(request, response);
        } else {
//            非登录 获取请求头token
            String jwt = request.getHeader("token");
//            为空拦截
            if (jwt == null || jwt.isEmpty()) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return;
            }
//            不为空则解析
            try {
                JwtUtils.parseJWT(jwt);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("解析令牌失败, 返回错误结果");
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return;
            }
//            解析通过放行
            filterChain.doFilter(request, response);
        }

    }
}
